package com.jrx.anytxn.transaction.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.*;
import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.customer.entity.CmCustomerBankcardInfo;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerBankcardInfoMapper;
import com.jrx.anytxn.customer.service.IBankCardService;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.PrDelqTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.entity.PrTransactionCodeTable;
import com.jrx.anytxn.param.service.product.IDelqTableService;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.service.system.ISystemParameterService;
import com.jrx.anytxn.param.service.system.ITransactionCodeTableService;
import com.jrx.anytxn.sharding.pojo.entity.CacheMapping;
import com.jrx.anytxn.sharding.service.ICacheMappingService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.dto.interfaceinfo.GlInterfaceInfoRes;
import com.jrx.anytxn.transaction.dto.loan.GlInterfaceReq;
import com.jrx.anytxn.transaction.dto.loan.GlInterfaceRes;
import com.jrx.anytxn.transaction.dto.loan.RecordGlInterfaceReq;
import com.jrx.anytxn.transaction.dto.loan.RecordGlInterfaceRes;
import com.jrx.anytxn.transaction.entity.*;
import com.jrx.anytxn.transaction.mapper.base.TlPaymentLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanAccountInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlGlInterfaceInfoMapper;
import com.jrx.anytxn.transaction.service.IGlInterfaceService;
import com.jrx.anytxn.transaction.service.IPaymentLogService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class GlInterfaceServiceImpl implements IGlInterfaceService {

    private static final Logger logger = LoggerFactory.getLogger(GlInterfaceServiceImpl.class);

    @Resource
    private ExtTlGlInterfaceInfoMapper extTlGlInterfaceInfoMapper;
    @Autowired
    private ITransactionCodeTableService transactionCodeTableService;
    @Autowired
    private ISegmentService segmentService;
    @Autowired
    IDelqTableService delqTableService;
    @Autowired
    private IPaymentLogService paymentLogService;
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private IProductTableService productTableService;
    @Resource
    private ExtAmLoanAccountInfoMapper extAmLoanAccountInfoMapper;
    @Resource
    private TlPaymentLogMapper tlPaymentLogMapper;
    @Resource
    private ExtAmLoanMainInfoMapper extAmLoanMainInfoMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired(required = false)
    private ICacheMappingService cacheMappingService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ExtCmCustomerBankcardInfoMapper extCmCustomerBankcardInfoMapper;
    @Autowired
    private ISystemParameterService iSystemParameterService;

    /**
     * 计提账户  生成计提gl
     *
     * @param businessDate
     * @param amInterestAccrualInfo
     * @return
     */
    @Override
    public TlGlInterfaceInfo generateGlInterfaceForAcccrual(Date businessDate, AmInterestAccrualInfo amInterestAccrualInfo) throws TxnException {
        if (amInterestAccrualInfo.getAccrualDailyProvision().subtract(amInterestAccrualInfo.getAccrualDailyTaxProvision()).compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }

        String tranCode = amInterestAccrualInfo.getTxnCode();
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(tranCode, amInterestAccrualInfo.getTenantId());
        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }
        String txnDesc = transactionCodeTable.getChineseName();

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amInterestAccrualInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(businessDate); //业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(businessDate, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amInterestAccrualInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(tranCode);//交易码
        tlGlInterfaceInfo.setAmount(amInterestAccrualInfo.getAccrualDailyProvision().subtract(amInterestAccrualInfo.getAccrualDailyTaxProvision()));//交易金额
        tlGlInterfaceInfo.setLoanId(amInterestAccrualInfo.getLoanId());//贷款id
        tlGlInterfaceInfo.setLoanProductId(amInterestAccrualInfo.getProductId());//贷款产品id
        tlGlInterfaceInfo.setCustomerId(amInterestAccrualInfo.getCustomerId());//客户号
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述
        tlGlInterfaceInfo.setTxnAccountId(amInterestAccrualInfo.getAccountId());//交易账户号
        tlGlInterfaceInfo.setLoanClassify(amInterestAccrualInfo.getLoanClassify());//五级分类
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amInterestAccrualInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amInterestAccrualInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amInterestAccrualInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amInterestAccrualInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(amInterestAccrualInfo.getAccountingPhase());
        tlGlInterfaceInfo.setLiabilityFlag(amInterestAccrualInfo.getLiabilityFlag());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    /**
     * 计提账户  生成税金计提gl
     *
     * @param businessDate
     * @param amInterestAccrualInfo
     * @return
     */
    @Override
    public TlGlInterfaceInfo generateGlInterfaceForAcccrualTax(Date businessDate, AmInterestAccrualInfo amInterestAccrualInfo) throws TxnException {
        if (amInterestAccrualInfo.getAccrualDailyTaxProvision().compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }

        String txnCode = amInterestAccrualInfo.getTxnCode();
        String tranCode = txnCode.substring(0, 1) + (Integer.parseInt(txnCode.substring(1)) + 3);
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(tranCode, amInterestAccrualInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }
        String txnDesc = transactionCodeTable.getChineseName();

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amInterestAccrualInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(businessDate); //业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(businessDate, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amInterestAccrualInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(tranCode);//交易码
        tlGlInterfaceInfo.setAmount(amInterestAccrualInfo.getAccrualDailyTaxProvision());//交易金额
        tlGlInterfaceInfo.setLoanId(amInterestAccrualInfo.getLoanId());//贷款id
        tlGlInterfaceInfo.setLoanProductId(amInterestAccrualInfo.getProductId());//贷款产品id
        tlGlInterfaceInfo.setCustomerId(amInterestAccrualInfo.getCustomerId());//客户号
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述
        tlGlInterfaceInfo.setTxnAccountId(amInterestAccrualInfo.getAccountId());//交易账户号
        tlGlInterfaceInfo.setLoanClassify(amInterestAccrualInfo.getLoanClassify());//五级分类
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amInterestAccrualInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amInterestAccrualInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amInterestAccrualInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amInterestAccrualInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(amInterestAccrualInfo.getAccountingPhase());
        tlGlInterfaceInfo.setAttributeReserve4((amInterestAccrualInfo.getAccrualDailyProvision().subtract(amInterestAccrualInfo.getAccrualDailyTaxProvision())).toPlainString());
        tlGlInterfaceInfo.setLiabilityFlag(amInterestAccrualInfo.getLiabilityFlag());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    @Override
    public TxnPage<GlInterfaceInfoRes> getGlInterfaceInfoByPage(String tenantId, Integer pageNum, Integer pageSize, String customerId, String loanId) throws TxnBizException {
        Page<GlInterfaceInfoRes> page = PageHelper.startPage(pageNum, pageSize);
        List<TlGlInterfaceInfo> glInterfaceInfoResList = extTlGlInterfaceInfoMapper.getAllTlGlInterfaceInfo(tenantId, customerId, loanId);
        if (glInterfaceInfoResList.isEmpty()) {
            logger.error("查询的总账流水表列表为空");
            throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getUserTips());
        }
        List<GlInterfaceInfoRes> res = BeanMapping.copyList(glInterfaceInfoResList, GlInterfaceInfoRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public GlInterfaceInfoRes getGlInterfaceInfoByPrimaryKey(Long id, String tenantId, String customerId) throws TxnBizException {
        if (id == null) {
            logger.error("总账流水表主键ID为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getCode(), TxnRespCode.NOT_EMPTY.getUserTips());
        }
        TlGlInterfaceInfo tlGlInterfaceInfo = extTlGlInterfaceInfoMapper.selectByPrimaryKeyAndCusIdAndTenantId(id, customerId, tenantId);
        if (null == tlGlInterfaceInfo) {
            logger.error("根据主键[{}]查询的总账流水表信息为空", id);
            throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getUserTips());
        }
        return BeanMapping.copy(tlGlInterfaceInfo, GlInterfaceInfoRes.class);
    }

    /**
     * 通过09交易账户生成gl流水
     *
     * @param paymentLog
     * @return
     */
    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(TlPaymentAllocationLog paymentLog) throws TxnException {
        logger.info("通过09交易账户生成gl流水,paymentLog:{}", BeanUtils.toMap(paymentLog));

        if (paymentLog.getPostingAmount().compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(paymentLog.getTxnCode()
                , paymentLog.getTenantId());
        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }
        TlGlInterfaceInfo gl = new TlGlInterfaceInfo();
        try {
            gl.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnException(TxnRespCode.ERROR.getUserTips());
        }
        gl.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));
        gl.setGlDate(paymentLog.getPostingDate());
        gl.setBatchId(DateUtils.format(paymentLog.getPostingDate(), DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);
        gl.setTenantId(paymentLog.getTenantId());
        gl.setAmount(paymentLog.getPostingAmount());
        gl.setLoanProductId(paymentLog.getProductId());
        gl.setTxnAccountId(paymentLog.getConnectAccountId());
        gl.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);
        gl.setOrganizationId(paymentLog.getOrganizationId());//　	机构号	　	同贷款订单表
        gl.setTxnCode(paymentLog.getTxnCode());//交易码
        gl.setLoanId(paymentLog.getLoanId());//贷款id
        gl.setCustomerId(paymentLog.getCustomerId());//客户号
        gl.setTxnAccountId(paymentLog.getAccountId());//交易账户号
        gl.setChannel(paymentLog.getChannel());
        gl.setLoanClassify(paymentLog.getLoanClassify());
        String txnDesc = transactionCodeTable.getChineseName();
        gl.setTxnDesc(txnDesc);
        gl.setCategory(paymentLog.getNonAccrualsFlag());
        gl.setAttributeReserve1(paymentLog.getTotalTenor().toString());
        gl.setAttributeReserve2(paymentLog.getTotalDays().toString());
        gl.setAttributeReserve3(paymentLog.getAccountingPhase());
        gl.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        gl.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        gl.setLiabilityFlag(paymentLog.getLiabilityFlag());
        gl.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号
        gl.setUpdateBy(TransBizConstant.SYS_OPRATE);
        gl.setSubChannel(this.getSubChannel(gl.getChannel(), gl.getCustomerId(), gl.getTenantId())); //子渠道
        logger.info("通过09交易账户生成gl流水,gl:{}", BeanUtils.toMap(gl));
        return gl;
    }

    /**
     * 通过09交易账户生成gl流水
     *
     * @param paymentLogList
     * @return
     */
    @Override
    public List<TlGlInterfaceInfo> buildTlGlInterfaceInfoList(List<TlPaymentAllocationLog> paymentLogList, AmLoanMainInfo amLoanMainInfo, AmLoanAccountInfo loanAccountInfo) throws TxnException {
        List<TlGlInterfaceInfo> glInterfaceInfoList = new ArrayList<>();
        for (TlPaymentAllocationLog paymentLog : paymentLogList) {
            //生成还款gl流水
            TlGlInterfaceInfo gl = this.buildTlGlInterfaceInfo(paymentLog);
            if (null != gl) {
                glInterfaceInfoList.add(gl);
            }

            String chargeOffFlag = loanAccountInfo.getChargeoffFlag();

            if (TransBizConstant.NON_ACCRUALS_FLA_1.equals(paymentLog.getNonAccrualsFlag()) && TransBizConstant.CHARGOFF_FLAG_0.equals(chargeOffFlag)) {
                PrDelqTable delqTable = delqTableService.findByDelqId(amLoanMainInfo.getTenantId(), amLoanMainInfo.getDelqTableId());
                //表外还款是否转回表内   是   生成表外转表内gl   否则不生成
                if (TransBizConstant.YES_FLAG.equals(delqTable.getNonAccrualsPaymentFlag())) {
                    //表外还款  生成表外转表内gl流水
                    BigDecimal glAmt = paymentLog.getPostingAmount().subtract(paymentLog.getTaxAmt());
                    String txnCode = "";

                    switch (paymentLog.getConnectAccountType()) {
                        //本金
                        case TransBizConstant.ACCOUNT_TYPE_06:
                            txnCode = TransBizConstant.TXN_CODE_PRIN_TRAN_INNON;
                            break;
                        //利息
                        case TransBizConstant.ACCOUNT_TYPE_04:
                            txnCode = TransBizConstant.TXN_CODE_INTR_TRAN_INNON;
                            //第5位为5  表内计提转表外的  区分交易码
                            if ("5".equals(paymentLog.getTxnCode().substring(4, 5))) {
                                txnCode = TransBizConstant.TXN_CODE_INTR_TRAN_OUT_INNON;
                            }
                            break;
                        //罚息
                        case TransBizConstant.ACCOUNT_TYPE_11:
                            txnCode = TransBizConstant.TXN_CODE_PENT_INTR_TRAN_INNON;
                            //第5位为5  表内计提转表外的  区分交易码
                            if ("5".equals(paymentLog.getTxnCode().substring(4, 5))) {
                                txnCode = TransBizConstant.TXN_CODE_PENT_INTR_TRAN_OUT_INNON;
                            }
                            break;
                        //复利
                        case TransBizConstant.ACCOUNT_TYPE_12:
                            txnCode = TransBizConstant.TXN_CODE_COMP_INTR_TRAN_INNON;
                            //第5位为5  表内计提转表外的  区分交易码
                            if ("5".equals(paymentLog.getTxnCode().substring(4, 5))) {
                                txnCode = TransBizConstant.TXN_CODE_COMP_INTR_TRAN_OUT_INNON;
                            }
                            break;
                    }
                    if (StringUtils.isNotEmpty(txnCode)) {
                        TlGlInterfaceInfo tranGl = this.buildTransferGlInterfaceInfo(paymentLog, glAmt, txnCode);
                        if (null != tranGl) {
                            glInterfaceInfoList.add(tranGl);
                        }
                    }
                }

            }
            //taxAmt税金大于0  需要处理税金   核销还款 或 表外还款
            if (paymentLog.getTaxAmt().compareTo(BigDecimal.ZERO) > 0) {
                //核销还款  表外还款  需要处理税金
                String txnCode = "";
                //核销还款
                if (paymentLog.getTxnCode().startsWith("T96")) {
                    if (TransBizConstant.ACCOUNT_TYPE_04.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CHARGEOFF_PAY_CODE_INTR_TAX;
                    } else if (TransBizConstant.ACCOUNT_TYPE_11.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CHARGEOFF_PAY_CODE_PEN_INTR_TAX;
                    } else if (TransBizConstant.ACCOUNT_TYPE_12.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CHARGEOFF_PAY_CODE_COMP_INTR_TAX;
                    }
                } else if (TransBizConstant.NON_ACCRUALS_FLA_1.equals(paymentLog.getNonAccrualsFlag()) && TransBizConstant.CHARGOFF_FLAG_0.equals(chargeOffFlag)) {
                    //表外还款
                    if (TransBizConstant.ACCOUNT_TYPE_04.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CODE_INTR_TAX_TRAN_INNON;
                        if ("5".equals(paymentLog.getTxnCode().substring(4, 5))) {
                            txnCode = TransBizConstant.TXN_CODE_INTR_TAX_TRAN_OUT_INNON;
                        }
                    } else if (TransBizConstant.ACCOUNT_TYPE_11.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CODE_PENT_INTR_TAX_TRAN_INNON;
                        if ("5".equals(paymentLog.getTxnCode().substring(4, 5))) {
                            txnCode = TransBizConstant.TXN_CODE_PENT_INTR_TAX_TRAN_OUT_INNON;
                        }
                    } else if (TransBizConstant.ACCOUNT_TYPE_12.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CODE_COMP_INTR_TAX_TRAN_INNON;
                        if ("5".equals(paymentLog.getTxnCode().substring(4, 5))) {
                            txnCode = TransBizConstant.TXN_CODE_COMP_INTR_TAX_TRAN_OUT_INNON;
                        }
                    }
                } else {
                    //普通还款  登记税金
                    if (TransBizConstant.ACCOUNT_TYPE_04.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CODE_INTR_TAX_PAYMENT;
                    } else if (TransBizConstant.ACCOUNT_TYPE_11.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CODE_PENT_INTR_TAX_PAYMENT;
                    } else if (TransBizConstant.ACCOUNT_TYPE_12.equals(paymentLog.getConnectAccountType())) {
                        txnCode = TransBizConstant.TXN_CODE_COMP_INTR_TAX_PAYMENT;
                    }
                }
                if (StringUtils.isNotEmpty(txnCode)) {
                    TlGlInterfaceInfo taxGl = this.buildTaxTransferGlInterfaceInfo(paymentLog, paymentLog.getPostingAmount(), paymentLog.getTaxAmt(), txnCode);
                    if (null != taxGl) {
                        glInterfaceInfoList.add(taxGl);
                    }
                }

            }
        }
        return glInterfaceInfoList;
    }

    /**
     * 通过09交易账户生成gl流水
     *
     * @param paymentLogList
     * @param amLoanMainInfoList
     * @param loanAccountInfoList
     * @return
     * @throws TxnException
     */
    @Override
    public List<TlGlInterfaceInfo> buildTlGlInterfaceInfoList(List<TlPaymentAllocationLog> paymentLogList, List<AmLoanMainInfo> amLoanMainInfoList, List<AmLoanAccountInfo> loanAccountInfoList) throws TxnException {
        List<TlGlInterfaceInfo> glInterfaceInfoList = new ArrayList<>();
        for (AmLoanMainInfo loanMainInfo : amLoanMainInfoList) {
            AmLoanAccountInfo loanAccountInfo = loanAccountInfoList.stream().filter(loanAcct -> loanMainInfo.getLoanId().equals(loanAcct.getLoanId())).findFirst().get();
            List<TlPaymentAllocationLog> logList = paymentLogList.stream().filter(log -> loanMainInfo.getLoanId().equals(log.getLoanId())).collect(Collectors.toList());
            List<TlGlInterfaceInfo> glList = this.buildTlGlInterfaceInfoList(logList, loanMainInfo, loanAccountInfo);
            if (CollectionUtils.isNotEmpty(glList)) {
                glInterfaceInfoList.addAll(glList);
            }
        }
        return glInterfaceInfoList;
    }


    private TlGlInterfaceInfo buildTransferGlInterfaceInfo(TlPaymentAllocationLog paymentLog, BigDecimal glAmt, String txnCode) throws TxnException {
        if (glAmt.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }

        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, paymentLog.getTenantId());
        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }
        TlGlInterfaceInfo gl = new TlGlInterfaceInfo();
        try {
            gl.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnException(TxnRespCode.ERROR.getUserTips());
        }
        gl.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));
        gl.setGlDate(paymentLog.getPostingDate());
        gl.setBatchId(DateUtils.format(paymentLog.getPostingDate(), DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);
        gl.setTenantId(paymentLog.getTenantId());
        gl.setAmount(glAmt);
        gl.setLoanProductId(paymentLog.getProductId());
        gl.setTxnAccountId(paymentLog.getConnectAccountId());
        gl.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);
        gl.setOrganizationId(paymentLog.getOrganizationId());//　	机构号	　	同贷款订单表
        gl.setTxnCode(txnCode);//交易码
        gl.setLoanId(paymentLog.getLoanId());//贷款id
        gl.setCustomerId(paymentLog.getCustomerId());//客户号
        gl.setTxnAccountId(paymentLog.getAccountId());//交易账户号
        gl.setChannel(paymentLog.getChannel());
        gl.setLoanClassify(paymentLog.getLoanClassify());
        String txnDesc = transactionCodeTable.getChineseName();
        gl.setTxnDesc(txnDesc);
        gl.setCategory(paymentLog.getNonAccrualsFlag());
        gl.setAttributeReserve1(paymentLog.getTotalTenor().toString());
        gl.setAttributeReserve2(paymentLog.getTotalDays().toString());
        gl.setAttributeReserve3(paymentLog.getAccountingPhase());
        gl.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        gl.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        gl.setLiabilityFlag(paymentLog.getLiabilityFlag());
        gl.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号
        gl.setUpdateBy(TransBizConstant.SYS_OPRATE);
        gl.setSubChannel(this.getSubChannel(gl.getChannel(), gl.getCustomerId(), gl.getTenantId())); //子渠道
        logger.info("通过09交易账户生成gl流水,gl:{}", BeanUtils.toMap(gl));
        return gl;
    }

    private TlGlInterfaceInfo buildTaxTransferGlInterfaceInfo(TlPaymentAllocationLog paymentLog, BigDecimal intrAmt, BigDecimal glAmt, String txnCode) throws TxnException {
        if (glAmt.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }

        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, paymentLog.getTenantId());
        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }
        TlGlInterfaceInfo gl = new TlGlInterfaceInfo();
        try {
            gl.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnException(TxnRespCode.ERROR.getUserTips());
        }
        gl.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));
        gl.setGlDate(paymentLog.getPostingDate());
        gl.setBatchId(DateUtils.format(paymentLog.getPostingDate(), DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);
        gl.setTenantId(paymentLog.getTenantId());
        gl.setAmount(glAmt);
        gl.setLoanProductId(paymentLog.getProductId());
        gl.setTxnAccountId(paymentLog.getConnectAccountId());
        gl.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);
        gl.setOrganizationId(paymentLog.getOrganizationId());//　	机构号	　	同贷款订单表
        gl.setTxnCode(txnCode);//交易码
        gl.setLoanId(paymentLog.getLoanId());//贷款id
        gl.setCustomerId(paymentLog.getCustomerId());//客户号
        gl.setTxnAccountId(paymentLog.getAccountId());//交易账户号
        gl.setChannel(paymentLog.getChannel());
        gl.setLoanClassify(paymentLog.getLoanClassify());
        String txnDesc = transactionCodeTable.getChineseName();
        gl.setTxnDesc(txnDesc);
        gl.setCategory(paymentLog.getNonAccrualsFlag());
        gl.setAttributeReserve1(paymentLog.getTotalTenor().toString());
        gl.setAttributeReserve2(paymentLog.getTotalDays().toString());
        gl.setAttributeReserve3(paymentLog.getAccountingPhase());
        gl.setAttributeReserve4(intrAmt.subtract(glAmt).toPlainString());
        gl.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        gl.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        gl.setLiabilityFlag(paymentLog.getLiabilityFlag());
        gl.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号
        gl.setUpdateBy(TransBizConstant.SYS_OPRATE);
        gl.setSubChannel(this.getSubChannel(gl.getChannel(), gl.getCustomerId(), gl.getTenantId())); //子渠道
        logger.info("通过09交易账户生成gl流水,gl:{}", BeanUtils.toMap(gl));
        return gl;
    }

    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(AmLoanMainInfo amLoanMainInfo,
                                                    AmLoanAccountInfo amLoanAccountInfo, String productName, Date business, String liabilityFlag) throws TxnException {

        if (amLoanMainInfo.getLoanAmount().compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(TransBizConstant.TXN_CODE_INSTSUM, amLoanMainInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amLoanAccountInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(business); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(business, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        tlGlInterfaceInfo.setLiabilityFlag(liabilityFlag);
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amLoanMainInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(TransBizConstant.TXN_CODE_INSTSUM);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(amLoanMainInfo.getLoanAmount());//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amLoanMainInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amLoanMainInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amLoanMainInfo.getCustomerId());//	客户号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnDesc(productName);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amLoanMainInfo.getLoanId());//交易账户号	　	贷款订单表-客户收款账号 TODO 放款配置改为loanId
        tlGlInterfaceInfo.setLoanClassify(amLoanAccountInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amLoanMainInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amLoanAccountInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amLoanMainInfo.getTotalTenor().toString());
        if (null != amLoanMainInfo.getTotalDays()) {
            tlGlInterfaceInfo.setAttributeReserve2(amLoanMainInfo.getTotalDays().toString());
        }
        tlGlInterfaceInfo.setAttributeReserve3(amLoanAccountInfo.getAccountingPhase());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(AmAccountMainInfo amAccountMainInfo, BigDecimal glAmt, String txnCode, String orgiStatus, Date business) throws TxnException {
        if (glAmt.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, amAccountMainInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amAccountMainInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(business); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(business, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amAccountMainInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(txnCode);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(glAmt);//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amAccountMainInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amAccountMainInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amAccountMainInfo.getCustomerId());//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amAccountMainInfo.getAccountId());//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(amAccountMainInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amAccountMainInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amAccountMainInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amAccountMainInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amAccountMainInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(orgiStatus);
        tlGlInterfaceInfo.setLiabilityFlag(amAccountMainInfo.getLiabilityFlag());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(AmInterestAccrualInfo amInterestAccrualInfo, BigDecimal glAmt, String txnCode, String orgiStatus, Date business) throws TxnException {
        if (glAmt.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, amInterestAccrualInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amInterestAccrualInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(business); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(business, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amInterestAccrualInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(txnCode);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(glAmt);//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amInterestAccrualInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amInterestAccrualInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amInterestAccrualInfo.getCustomerId());//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amInterestAccrualInfo.getAccountId());//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(amInterestAccrualInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amInterestAccrualInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amInterestAccrualInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amInterestAccrualInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amInterestAccrualInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(orgiStatus);
        tlGlInterfaceInfo.setLiabilityFlag(amInterestAccrualInfo.getLiabilityFlag());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(AmInterestAccrualInfo amInterestAccrualInfo, String txnCode, String orgiStatus, Date business) throws TxnException {
        return this.buildTlGlInterfaceInfo(amInterestAccrualInfo, amInterestAccrualInfo.getAccrualTotalAccruInterest(), txnCode, orgiStatus, business);
    }

    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(AmLoanAccountInfo amLoanAccountInfo, AmLoanMainInfo amLoanMainInfo, String txnCode, String orgiStatus, Date bussinessDate, String prinNonAccrualFlag) throws TxnException {
        BigDecimal glAmt = amLoanAccountInfo.getRemainPrincipal().subtract(amLoanAccountInfo.getPrincipalBalance());
        if (glAmt.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, amLoanAccountInfo.getTenantId());
        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amLoanAccountInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(bussinessDate); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(bussinessDate, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amLoanAccountInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(txnCode);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(glAmt);//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amLoanAccountInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amLoanAccountInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amLoanAccountInfo.getCustomerId());//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amLoanAccountInfo.getLoanId());//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(amLoanAccountInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amLoanAccountInfo.getChannel());//渠道	　	同贷款订单表
        String category = TransBizConstant.NON_ACCRUALS_FLA_0;
        if (TransBizConstant.TRANSFER_FLAG_1.equals(prinNonAccrualFlag)) {
            //本金转非应计   非应计类别取订单账户    否则为0应计
            category = amLoanAccountInfo.getNonAccrualsFlag();
        }
        tlGlInterfaceInfo.setCategory(category);
        tlGlInterfaceInfo.setAttributeReserve1(amLoanMainInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amLoanMainInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(orgiStatus);
        tlGlInterfaceInfo.setLiabilityFlag(TransBizConstant.LIABILITY_FLAG_00);
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    /**
     * 生成取消订单GL
     *
     * @param orgiGl
     * @param businessDate
     * @return
     * @throws SegmentException
     */
    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(TlGlInterfaceInfo orgiGl, Date businessDate) throws TxnException {
        String cancleTxnCode = this.getCancleTxnCode(orgiGl.getTxnCode());
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(cancleTxnCode, orgiGl.getTenantId());
        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo saveGl = new TlGlInterfaceInfo();
        BeanMapping.copy(orgiGl, saveGl);
        try {
            saveGl.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        saveGl.setBatchId(DateUtils.format(businessDate, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);
        saveGl.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));
        if (cancleTxnCode.equals(orgiGl.getTxnCode())) {
            saveGl.setAmount(orgiGl.getAmount().negate());
        } else {
            saveGl.setAmount(orgiGl.getAmount());
        }
        saveGl.setTxnCode(cancleTxnCode);
        saveGl.setTxnDesc(transactionCodeTable.getChineseName());
        saveGl.setGlDate(businessDate);
        saveGl.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        return saveGl;
    }

    @Override
    public TlGlInterfaceInfo buildTlGlInterfaceInfo(String productId, String tenantId, String orgId, String txnCode, BigDecimal glAmt, String classify, Date businessDate) throws TxnException {
        if (glAmt.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, tenantId);

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        tlGlInterfaceInfo.setTenantId(tenantId);
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(businessDate); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(businessDate, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(orgId);//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(txnCode);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(glAmt);//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId("0");//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(productId);//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId("0");//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId("0");//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(classify);//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel("0");//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory("0");
        tlGlInterfaceInfo.setLiabilityFlag(TransBizConstant.LIABILITY_FLAG_00);
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel("0"); //子渠道
        return tlGlInterfaceInfo;
    }

    @Override
    public GlInterfaceRes buildTlGlInterfaceInfo(GlInterfaceReq req) throws TxnException {
        GlInterfaceRes res = new GlInterfaceRes();

        if (req.getAmount().compareTo(BigDecimal.ZERO) == 0) {
            res.setSunStatus(TransBizConstant.GL_STATUS_F);
            return res;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(req.getTxnCode(), req.getTenantId());

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        tlGlInterfaceInfo.setTenantId(req.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(req.getGlDate()); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(req.getGlDate(), DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(req.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(req.getTxnCode());//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(req.getAmount());//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId("0");//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(req.getLoanProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId("0");//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId("0");//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify("0");//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel("0");//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory("0");
        tlGlInterfaceInfo.setLiabilityFlag(TransBizConstant.LIABILITY_FLAG_00);
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel("0"); //子渠道
        extTlGlInterfaceInfoMapper.insertSelective(tlGlInterfaceInfo);

        res.setSunStatus(TransBizConstant.GL_STATUS_S);
        return res;
    }

    @Override
    public TlGlInterfaceInfo buildTaxTlGlInterfaceInfo(AmAccountMainInfo amAccountMainInfo, BigDecimal intrAmt, BigDecimal taxAmt, String txnCode, String orgiStatus, Date business) throws TxnException {
        if (taxAmt.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, amAccountMainInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amAccountMainInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(business); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(business, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amAccountMainInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(txnCode);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(amAccountMainInfo.getTaxAmt());//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amAccountMainInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amAccountMainInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amAccountMainInfo.getCustomerId());//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amAccountMainInfo.getAccountId());//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(amAccountMainInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amAccountMainInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amAccountMainInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amAccountMainInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amAccountMainInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(orgiStatus);
        tlGlInterfaceInfo.setAttributeReserve4(intrAmt.subtract(taxAmt).toPlainString());
        tlGlInterfaceInfo.setLiabilityFlag(amAccountMainInfo.getLiabilityFlag());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    @Override
    public TlGlInterfaceInfo buildTaxTlGlInterfaceInfo(AmInterestAccrualInfo amInterestAccrualInfo, BigDecimal intrAmt, BigDecimal taxAmt, String txnCode, String orgiStatus, Date business) throws TxnException {
        if (taxAmt.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(txnCode, amInterestAccrualInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amInterestAccrualInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(business); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(business, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amInterestAccrualInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(txnCode);//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(taxAmt);//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amInterestAccrualInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amInterestAccrualInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amInterestAccrualInfo.getCustomerId());//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amInterestAccrualInfo.getAccountId());//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(amInterestAccrualInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amInterestAccrualInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(amInterestAccrualInfo.getNonAccrualsFlag());
        tlGlInterfaceInfo.setAttributeReserve1(amInterestAccrualInfo.getTotalTenor().toString());
        tlGlInterfaceInfo.setAttributeReserve2(amInterestAccrualInfo.getTotalDays().toString());
        tlGlInterfaceInfo.setAttributeReserve3(orgiStatus);
        tlGlInterfaceInfo.setAttributeReserve4((intrAmt.subtract(taxAmt)).toPlainString());
        tlGlInterfaceInfo.setLiabilityFlag(amInterestAccrualInfo.getLiabilityFlag());
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

    private String getCancleTxnCode(String txnCode) {
        switch (txnCode) {
            case TransBizConstant.TXN_CODE_INSTSUM:
                return TransBizConstant.TXN_CODE_INSTSUM_REVOCATION;
            case TransBizConstant.TXN_CODE_INST_INTR_ACCU:
                return TransBizConstant.TXN_CODE_INTR_REVOCATION;
            case TransBizConstant.TXN_CODE_PEN_INTR_ACCU:
                return TransBizConstant.TXN_CODE_PENT_INTR_REVOCATION;
            case TransBizConstant.TXN_CODE_COM_INTR_ACCU:
                return TransBizConstant.TXN_CODE_COMP_INTR_REVOCATION;
            case TransBizConstant.TXN_CODE_INST_INTR_TAX_ACCU:
                return TransBizConstant.TXN_CODE_INTR_TAX_REVOCATION;
            case TransBizConstant.TXN_CODE_PEN_INTR_TAX_ACCU:
                return TransBizConstant.TXN_CODE_PENT_INTR_TAX_REVOCATION;
            case TransBizConstant.TXN_CODE_COM_INTR_TAX_ACCU:
                return TransBizConstant.TXN_CODE_COMP_INTR_TAX_REVOCATION;
            case TransBizConstant.TXN_CODE_INST_WAIVE_INTR_ACCU:
                return TransBizConstant.TXN_CODE_WAIVE_INTR_REVOCATION;
            case TransBizConstant.TXN_CODE_INST_WAIVE_INTR_TAX_ACCU:
                return TransBizConstant.TXN_CODE_WAIVE_INTR_TAX_REVOCATION;
            case TransBizConstant.TXN_CODE_MARKETING_FEE:
                return TransBizConstant.TXN_CODE_MARKETING_RECOVERY_FEE;
            default:
                return txnCode;
        }
    }

    /**
     * 总账流水记账
     *
     * @param req 总账流水记账请求
     * @return RecordGlInterfaceRes
     * @throws TxnException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecordGlInterfaceRes buildTlGlInterfaceInfo(RecordGlInterfaceReq req) throws TxnException {
        logger.info("总账流水记账请求参数{}", JSON.toJSONString(req));

        RecordGlInterfaceRes res = new RecordGlInterfaceRes();

        String tenantId = req.getTenantId();
        CacheMapping cacheMapping = cacheMappingService.selectByUserIdAndChannel(tenantId, req.getUserId(), req.getChannel());
        if (cacheMapping == null && StringUtils.isBlank(cacheMapping.getCustomerId())) {
            logger.error("租户id[{}],用户[{}],渠道[{}]对应的客户id不存在", tenantId, req.getUserId(), req.getChannel());
            throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getMsg());
        }
        String customerId = cacheMapping.getCustomerId();

        PrOrganizationTable organizationTable = organizationTableService.findByOrId(TransBizConstant.DEFAULT_ORG_ID, tenantId);
        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(req.getTransactionCode(), tenantId);
        AmLoanAccountInfo amLoanAccountInfo = extAmLoanAccountInfoMapper.selectByLoanId(req.getLoanId(), customerId, tenantId);
        AmLoanMainInfo amLoanMainInfo = extAmLoanMainInfoMapper.selectByLoanIdAndCusId(req.getLoanId(), customerId, tenantId);
        if(StringUtils.isNotBlank(req.getMerchantName())){
            amLoanMainInfo.setMerchantId(req.getMerchantId());
            amLoanMainInfo.setMerchantName(req.getMerchantName());
            extAmLoanMainInfoMapper.updateByLoanId(amLoanMainInfo);
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        tlGlInterfaceInfo.setTenantId(tenantId);
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(organizationTable.getNextProcessingDate()); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(organizationTable.getNextProcessingDate(), DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(organizationTable.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(req.getTransactionCode());//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(req.getAmount());//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(req.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amLoanAccountInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(customerId);//	客户号	　	同贷款订单表
        String txnDesc = transactionCodeTable.getChineseName();
        tlGlInterfaceInfo.setTxnDesc(txnDesc);//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId("0");//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(amLoanAccountInfo.getLoanClassify());//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(req.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory("0");
        tlGlInterfaceInfo.setLiabilityFlag(TransBizConstant.LIABILITY_FLAG_00);
        tlGlInterfaceInfo.setAttributeReserve1(String.valueOf(amLoanMainInfo.getTotalTenor()));// 总期数
        tlGlInterfaceInfo.setAttributeReserve2(String.valueOf(amLoanMainInfo.getTotalDays()));// 贷款期限总天数
        tlGlInterfaceInfo.setAttributeReserve3(amLoanAccountInfo.getAccountingPhase());// 会计状态
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        if (TransBizConstant.REPAYMENT_TYPE_REFUND.equals(req.getTransactionType())) {
            PrProductTable product = productTableService.findProByProIdAndOrgId(amLoanMainInfo.getProductId(), amLoanMainInfo.getOrganizationId(), amLoanMainInfo.getTenantId());
            CustomerRes customer = customerService.getCustomerByChannelAndUserId(amLoanMainInfo.getChannel(),
                    req.getUserId(), amLoanMainInfo.getTenantId());
            CmCustomerBankcardInfo customerBank;
            try {
                customerBank = bankCardService.getBankCardByCondition(customer.getSecondLevel().getCustomerId(), TransBizConstant.Y_FLAG,
                        null, amLoanMainInfo.getChannel(), amLoanMainInfo.getTenantId());
            } catch (TxnBizException e) {
                logger.warn("该{}客户无默认还款卡", customer.getSecondLevel().getCustomerId());
                String extFields = amLoanMainInfo.getExtFields();
                JSONObject jsonObject = JSONObject.parseObject(extFields);
                //  收款人银行账号
                Object recverBankAcctNo = jsonObject.get("RECVER_BANK_ACCT_NO");
                // 收款人银行行号
                Object recverBankBankNo = jsonObject.get("RECVER_BANK_BANK_NO");
                // 收款人银行全称
                Object recverBankFullname = jsonObject.get("RECVER_BANK_FULLNAME");
                CmCustomerBankcardInfo bank = new CmCustomerBankcardInfo();
                bank.setBankId(getString(recverBankBankNo));
                bank.setBankName(getString(recverBankFullname));
                bank.setCardNumber(getString(recverBankAcctNo));
                // 商户退款
                bank.setCardType("7");
                customerBank = new CmCustomerBankcardInfo();
                org.springframework.beans.BeanUtils.copyProperties(bank, customerBank);
                logger.warn("总账流水记账信息：{}",JSONObject.toJSONString(bank));
            }
            TlPaymentLog paymentLog = paymentLogService.buildTlPaymentLog(TransBizConstant.REPAYMENT_TYPE_REFUND,
                    customerBank, customer, req.getAmount(),
                    organizationTable.getNextProcessingDate(), product, req);
            paymentLog.setUpdateBy(req.getUserId());
            paymentLog.setPayId(req.getSeqNo());
            paymentLog.setRefNo(req.getSeqNo());
            paymentLog.setSubChannel(amLoanMainInfo.getSubChannel());
            paymentLog.setThirdChannel(amLoanMainInfo.getThirdChannel());
            paymentLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), organizationTable.getNextProcessingDate()));
            paymentLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_S);
            tlPaymentLogMapper.insertSelective(paymentLog);
        }
        extTlGlInterfaceInfoMapper.insertSelective(tlGlInterfaceInfo);

        res.setGlFlowno(tlGlInterfaceInfo.getGlFlowno());
        res.setLoanId(tlGlInterfaceInfo.getLoanId());
        res.setUserId(req.getUserId());

        return res;
    }

    /**
     * 转换成string
     * @param o
     * @return
     */
    public String getString(Object o) {
        return Objects.isNull(o) ? "" : o.toString();
    }

    /**
     * 获取子渠道
     *
     * @param channel    渠道id
     * @param customerId 客户id
     * @param tenantId   租户id
     * @return String
     * @throws TxnBizException
     */
    private String getSubChannel(String channel, String customerId, String tenantId) throws TxnBizException {
        CmCustomerSecondLevel cmCustomerSecondLevel = customerService.getSecondByChannelAndCustomerIdAndTensnId(channel, customerId, tenantId, null);
        return cmCustomerSecondLevel.getSubChannel();
    }


    @Override
    public TlGlInterfaceInfo buildRefundGl(AmLoanMainInfo amLoanMainInfo, BigDecimal refundAmt, Date business) throws TxnException {

        PrTransactionCodeTable transactionCodeTable = transactionCodeTableService.findByCodeAndTenantId(TransBizConstant.TXN_CODE_REFUND_MORE, amLoanMainInfo.getTenantId());

        if (TransBizConstant.GENERAL_LEDGER_FLAG_0.equals(transactionCodeTable.getGeneralLedgerFlag())) {
            return null;
        }

        TlGlInterfaceInfo tlGlInterfaceInfo = new TlGlInterfaceInfo();
        try {
            tlGlInterfaceInfo.setId(segmentService.getId(TransBizConstant.TL_GL_INTERFACE_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlGlInterfaceInfo.setTenantId(amLoanMainInfo.getTenantId());
        tlGlInterfaceInfo.setGlFlowno(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));//流水号 	调用统一的工具类得到全局流水号
        tlGlInterfaceInfo.setGlDate(business); //业务日期	YYYY-MM-DD	当前业务日期
        tlGlInterfaceInfo.setBatchId(DateUtils.format(business, DateUtils.DATE_PATTERN_ANOTHER) + TransBizConstant.BATCH_NUMBER);//批次号
        tlGlInterfaceInfo.setLiabilityFlag(TransBizConstant.LIABILITY_FLAG_00);
        // 业务日期 +01
        // 源系统可以按照一定逻辑生成（比如每次生成一个数据文件，同时生成一个批次号），目前一阶段每日仅有一个批次文件，规则：YYYYMMDD＋01
        // 	YYYYMMDD＋01
        tlGlInterfaceInfo.setOrganizationId(amLoanMainInfo.getOrganizationId());//　	机构号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnCode(transactionCodeTable.getTransactionCode());//交易码 已有	消费信贷核算事件对应的交易码 具体值：按照消费信贷系统规范约定会计引擎模块会维护与消费信贷系统一致的数据字典
        tlGlInterfaceInfo.setAmount(refundAmt);//交易金额	　	贷款订单表-贷款金额
        tlGlInterfaceInfo.setLoanId(amLoanMainInfo.getLoanId());//贷款id	　	同贷款订单表
        tlGlInterfaceInfo.setLoanProductId(amLoanMainInfo.getProductId());//　	贷款产品id	　	同贷款订单表
        tlGlInterfaceInfo.setCustomerId(amLoanMainInfo.getCustomerId());//	客户号	　	同贷款订单表
        tlGlInterfaceInfo.setTxnDesc(transactionCodeTable.getChineseName());//交易描述	业务行摘要说明，源系统可视情况自动生成  产品名称
        tlGlInterfaceInfo.setTxnAccountId(amLoanMainInfo.getLoanId());//交易账户号	　	贷款订单表-客户收款账号
        tlGlInterfaceInfo.setLoanClassify(TransBizConstant.LOAN_CLASSIFY_0);//五级分类	 同贷款订单表
        tlGlInterfaceInfo.setImpairFlag(TransBizConstant.NO_FLAG);//贷款是否发生单笔减值	0 = 否   1 = 是 	初始固定值：0
        tlGlInterfaceInfo.setGlSource(TransBizConstant.GL_INTERFACE_SOURCE);//数据来源	固定值CLS	固定值 CLS
        tlGlInterfaceInfo.setChannel(amLoanMainInfo.getChannel());//渠道	　	同贷款订单表
        tlGlInterfaceInfo.setCategory(TransBizConstant.NON_ACCRUALS_FLA_0);
        tlGlInterfaceInfo.setAttributeReserve1(amLoanMainInfo.getTotalTenor().toString());
        if (null != amLoanMainInfo.getTotalDays()) {
            tlGlInterfaceInfo.setAttributeReserve2(amLoanMainInfo.getTotalDays().toString());
        }
        tlGlInterfaceInfo.setAttributeReserve3(TransBizConstant.ACCOUNTING_PHASE_0);
        tlGlInterfaceInfo.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);//	记录版本号	　	初始值：
        tlGlInterfaceInfo.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlGlInterfaceInfo.setSubChannel(this.getSubChannel(tlGlInterfaceInfo.getChannel(), tlGlInterfaceInfo.getCustomerId(), tlGlInterfaceInfo.getTenantId())); //子渠道
        return tlGlInterfaceInfo;
    }

}
